<?php

declare(strict_types=1);

namespace App\Controller;


use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Di\Container;
use Hyperf\Server\ServerFactory;
use Swoole\Http\Request;
use Swoole\Server;
use Swoole\Websocket\Frame;
use Swoole\WebSocket\Server as WebSocketServer;

class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    public $container;

    public function __construct(Container $container)
    {
        $this->container = $container;

    }

    /**
     * 发送消息
     * @param WebSocketServer $server
     * @param Frame $frame
     */
    public function onMessage(WebSocketServer $server, Frame $frame): void
    {

        $server->push($frame->fd, 'Recv: ' . $frame->data);

    }

    /**
     * 客户端失去链接
     * @param Server $server
     * @param int $fd
     * @param int $reactorId
     */
    public function onClose(Server $server, int $fd, int $reactorId): void
    {
        //移除集合中指定的value
        dump('closed');

    }

    /**
     * 客户端链接
     * @param WebSocketServer $server
     * @param Request $request
     */
    public function onOpen(WebSocketServer $server, Request $request): void
    {

//        $server = $this->container->get(ServerFactory::class)->getServer()->getServer();
//        dump($server);
        $server->push($request->fd, 'Opened');

    }
}
